import { mount } from '../common/mount';
import VNode from '../common/VNode';
import { patchChildren } from './patchChildren';
import { patchProps } from './patchProps';

export const patch = function (oldVNode: VNode, newVNode: VNode, container?: HTMLElement | null) {
  // 1. 节点类型不同直接挂载
  if (
    newVNode.tag !== oldVNode.tag ||
    (newVNode.text !== null && oldVNode.text !== null && newVNode.text !== oldVNode.text)
  ) {
    const oldEL = (oldVNode.el as HTMLElement) || container;
    const parent = (oldEL?.parentNode as HTMLElement) || container;
    mount(newVNode, parent);
    if (oldVNode.el !== null) {
      parent.removeChild(oldVNode.el as HTMLElement);
    }
    return;
  }
  // 2.对比文本内容
  if (newVNode.text !== oldVNode.text) {
    (oldVNode.el as HTMLElement).textContent = newVNode.text;
    newVNode.el = oldVNode.el; // 复用真实 DOM
    return;
  }
  // 3.复用真实DOM
  newVNode.el = oldVNode.el; // 复用真实 DOM
  const newEL = newVNode.el as HTMLElement;

  // 4.对比属性
  patchProps(newEL, oldVNode.props, newVNode.props);
  // 5.对比子节点
  patchChildren(newEL, oldVNode.children as VNode[], newVNode.children as VNode[]);
};
